﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Payton.WP7.Common;
using Payton.WP7.Common.Model;
using Payton.WP7.ViewModel;
using System.IO.IsolatedStorage;
using System.IO;
using System.Windows.Media.Imaging;

namespace Payton.WP7.Views
{
    public partial class UserHomeView : PhoneApplicationPage
    {
        private bool hasInit = false;
        private UserHomeViewModel _userHomeViewModel;
        private ScrollViewer _tweetListScrollViewer;
        private ScrollViewer _friendListScrollViewer;
        private ScrollViewer _followerListScrollViewer;

        public UserHomeView()
        {
            InitializeComponent();

            Loaded += (o, e) =>
            {
                if (hasInit)
                    return;
                hasInit = true;

                var q = NavigationContext.QueryString.FirstOrDefault();

                if (q.Key == null)
                {
                    return;
                }
                else if (!PhoneApplicationService.Current.State.ContainsKey(q.Key))
                {
                    _userHomeViewModel = new UserHomeViewModel(q.Key, int.Parse(q.Value));
                }
                else
                {
                    var user = PhoneApplicationService.Current.State[q.Key];
                    PhoneApplicationService.Current.State.Remove(q.Key);
                    _userHomeViewModel = new UserHomeViewModel(user as SNSUser);
                }



                _userHomeViewModel.OnTweetsRefreshed += () =>
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        if (_tweetListScrollViewer == null && _userHomeViewModel.Items.Count > 0)
                        {
                            _tweetListScrollViewer = tweetList.GetChild<ScrollViewer>();
                            _tweetListScrollViewer.ManipulationCompleted += (sender, eventArgs) =>
                            {
                                if (eventArgs.TotalManipulation.Translation.Y < -100 && _tweetListScrollViewer.VerticalOffset >= _tweetListScrollViewer.ScrollableHeight)
                                {
                                    _userHomeViewModel.NextPageOfTweets(false);
                                }
                                else if (eventArgs.TotalManipulation.Translation.Y > 100 && _tweetListScrollViewer.VerticalOffset <= 0)
                                {
                                    _userHomeViewModel.RefreshTimeLineOfTweets(false);
                                }
                            };
                        }
                    });
                };
                _userHomeViewModel.OnFriendsRefreshed += () =>
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        if (_friendListScrollViewer == null && _userHomeViewModel.Friends.Count > 0)
                        {
                            _friendListScrollViewer = friendList.GetChild<ScrollViewer>();
                            _friendListScrollViewer.ManipulationCompleted += (sender, eventArgs) =>
                            {
                                if (eventArgs.TotalManipulation.Translation.Y < -100 && _friendListScrollViewer.VerticalOffset >= _friendListScrollViewer.ScrollableHeight)
                                {
                                    _userHomeViewModel.NextPageOfFriends(false);
                                }
                                //else if (eventArgs.TotalManipulation.Translation.Y > 100 && _friendListScrollViewer.VerticalOffset <= 0)
                                //{
                                //    _userHomeViewModel.RefreshTimeLineOfFriends();
                                //}
                            };
                        }
                    });
                };
                _userHomeViewModel.OnFollowersRefreshed += () =>
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        if (_followerListScrollViewer == null && _userHomeViewModel.Followers.Count > 0)
                        {
                            _followerListScrollViewer = followerList.GetChild<ScrollViewer>();
                            _followerListScrollViewer.ManipulationCompleted += (sender, eventArgs) =>
                            {
                                if (eventArgs.TotalManipulation.Translation.Y < -100 && _followerListScrollViewer.VerticalOffset >= _followerListScrollViewer.ScrollableHeight)
                                {
                                    _userHomeViewModel.NextPageOfFollowers(false);
                                }
                                //else if (eventArgs.TotalManipulation.Translation.Y > 100 && _followerListScrollViewer.VerticalOffset <= 0)
                                //{
                                //    _userHomeViewModel.RefreshTimeLineOfFollowers();
                                //}
                            };
                        }
                    });
                };
                DataContext = _userHomeViewModel;

                _userHomeViewModel.PropertyChanged += (s, i) =>
                {
                    if (i.PropertyName == "Loading")
                    {
                        if (_userHomeViewModel.Loading)
                        {
                            progressIndicator.IsIndeterminate = true;
                            HideMenu();
                        }
                        else
                        {
                            progressIndicator.IsIndeterminate = false;
                            PopulateMenu();
                        }
                    }
                    if (i.PropertyName == "PivotSelectedIndex")
                    {
                        switch (_userHomeViewModel.PivotSelectedIndex)
                        {
                            case 1:
                                if (_userHomeViewModel.Friends.Count <= 0)
                                    _userHomeViewModel.NextPageOfFriends(true);
                                break;
                            case 2:
                                if (_userHomeViewModel.Followers.Count <= 0)
                                    _userHomeViewModel.NextPageOfFollowers(true);
                                break;
                            default:
                                break;
                        }
                    }
                };
            };
        }

        private void SetAppIconButton(int p)
        {

        }

        private void OnUserSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                var user = e.AddedItems[0] as SNSUser;
                var key = user.AccountName + "=" + user.AccountID;

                if (PhoneApplicationService.Current.State.ContainsKey(key))
                {
                    PhoneApplicationService.Current.State.Remove(key);
                }

                PhoneApplicationService.Current.State.Add(key, user);
                NavigationService.Navigate(new Uri("/Views/UserHomeView.xaml?" + key, UriKind.Relative));
            }
        }

        private void OnStatusSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                var status = (e.AddedItems[0] as SNSStatusViewModel).Item;
                var key = status.Id.ToString();

                if (PhoneApplicationService.Current.State.ContainsKey(key))
                {
                    PhoneApplicationService.Current.State.Remove(key);
                }

                PhoneApplicationService.Current.State.Add(key, status);
                NavigationService.Navigate(new Uri("/Views/StatusDetailView.xaml?" + key, UriKind.Relative));
            }
        }

        private void privateMessage_Click(object sender, EventArgs e)
        {
            _userHomeViewModel.SendMessageMethod();
        }

        private void refresh_Click(object sender, EventArgs e)
        {
            _userHomeViewModel.RefreshTimeLineOfTweets(false);
        }

        private void follow_Click(object sender, EventArgs e)
        {
            _userHomeViewModel.FollowMethod();
        }

        private void unfollow_Click(object sender, EventArgs e)
        {
            _userHomeViewModel.UnfollowMethod();
        }

        private void PopulateMenu()
        {
            if (_userHomeViewModel.User == null)
            {
                return;
            }

            var isFollowing = _userHomeViewModel.User.Following;
            var btn1 = null as ApplicationBarIconButton;
            var btn2 = null as ApplicationBarIconButton;
    
            var users = AccountManager.Current.GetAllAccount();
            var isSelf = users.Any(i => i.UserLite.Equals(_userHomeViewModel.User));
            var isSina = _userHomeViewModel.User.ServiceProvider == SNSProviderType.Sina;
            var miHome = null as ApplicationBarMenuItem;

            this.ApplicationBar.Buttons.Clear();

            btn1 = new ApplicationBarIconButton
            {
                IconUri = new Uri("/Images/AppBarIcons/appbar.tweet.bubble.update.png", UriKind.Relative),
                Text = AppResx.PrivateText,
            };
            btn1.Click += privateMessage_Click;

            if (!isFollowing)
            {
                btn2 = new ApplicationBarIconButton
                {
                    IconUri = new Uri("/Images/AppBarIcons/appbar_follow.png", UriKind.Relative),
                    Text = AppResx.FollowText,
                };
                btn2.Click += follow_Click;
            }
            else
            {
                btn2 = new ApplicationBarIconButton
                {
                    IconUri = new Uri("/Images/AppBarIcons/appbar_unfollow.png", UriKind.Relative),
                    Text = AppResx.UnfollowText,
                };
                btn2.Click += unfollow_Click;
            }

          

            if (!isSina && !isSelf)
            {
                this.ApplicationBar.Buttons.Add(btn1);
            }

            if (!isSelf)
            {
                this.ApplicationBar.Buttons.Add(btn2);
            }

            var user = _userHomeViewModel.User;

            if (ShellTile.ActiveTiles.Any(x => x.NavigationUri.ToString().Contains(user.AccountName + "=" + user.AccountID)))
            {

            }
            else
            {
                var btnPin = new ApplicationBarIconButton
                {
                    IconUri = new Uri("/Images/AppBarIcons/pin.png", UriKind.Relative),
                    Text = AppResx.PinToStart,
                };
                btnPin.Click += new EventHandler(btnPin_Click);
                this.ApplicationBar.Buttons.Add(btnPin);
            }
                

            miHome = new ApplicationBarMenuItem
            {
                Text = AppResx.HomePageText,
            };
            miHome.Click += GoToHomePage;

            this.ApplicationBar.MenuItems.Clear();
            this.ApplicationBar.MenuItems.Add(miHome);

            if (!this.ApplicationBar.IsVisible
                && (this.ApplicationBar.Buttons.Count > 0 || this.ApplicationBar.MenuItems.Count > 0))
                this.ApplicationBar.IsVisible = true;
            //throw new NotImplementedException();
        }

        void btnPin_Click(object sender, EventArgs e)
        {
            // Look to see if the tile already exists and if so, don't try to create again.
            var user = _userHomeViewModel.User;
            ShellTile TileToFind = ShellTile.ActiveTiles.FirstOrDefault(x => x.NavigationUri.ToString().Contains("?" + user.AccountName + "=" + user.AccountID));

            // Create the tile if we didn't find it already exists.
            if (TileToFind == null)
            {
                // Create the tile object and set the properties for the tile.

                if (_userHomeViewModel.ProfileImage != null && _userHomeViewModel.ProfileImage is BitmapSource)
                {
                    byte[] data;
                    using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        var path = string.Format("/Shared/ShellContent/{0}.jpg",user.AccountName+"head");
                        if (file.FileExists(path))
                            file.DeleteFile(path);

                        using (IsolatedStorageFileStream fileStream = file.OpenFile(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                        {
                            // Get an Image Stream
                            using (MemoryStream ms = new MemoryStream())
                            {
                                var ImageToSend = _userHomeViewModel.ProfileImage as BitmapSource;
                                
                                WriteableBitmap btmMap = new WriteableBitmap(ImageToSend);

                                // write an image into the stream
                                Extensions.SaveJpeg(btmMap, ms,
                                    173, 173, 0, 100);

                                // reset the stream pointer to the beginning
                                ms.Seek(0, 0);
                                //read the stream into a byte array
                                data = new byte[ms.Length];
                                ms.Read(data, 0, data.Length);
                            }
                            fileStream.Write(data, 0, data.Length);
                            fileStream.Close();
                        }
                    }
                }
                var uri = new Uri(string.Format("isostore:/Shared/ShellContent/{0}.jpg", user.AccountName + "head"), UriKind.Absolute);
                var lastStatus = _userHomeViewModel.Items.FirstOrDefault();
                StandardTileData NewTileData = new StandardTileData
                {
                    BackgroundImage = uri,
                    Title = user.Name,
                    Count = 0,
                    BackTitle = user.Name,
                    BackContent = lastStatus!=null?lastStatus.Item.Text:"",
                };
                //BackBackgroundImage = new Uri("/Images/Blue.jpg", UriKind.Relative)
                // Create the tile and pin it to Start. This will cause a navigation to Start and a deactivation of our application.
                ShellTile.Create(new Uri(string.Format("/Views/UserHomeView.xaml?{0}={1}", user.AccountName, user.AccountID), UriKind.Relative), NewTileData);
            }

            //throw new NotImplementedException();
        }

        private void HideMenu()
        {
            if (this.ApplicationBar.IsVisible)
                this.ApplicationBar.IsVisible = false;
            //throw new NotImplementedException();
        }

        private void GoToHomePage(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/MainView.xaml", UriKind.Relative));
        }
    }
}
